<template>
  <el-dialog
    title="选择经费类别"
    v-model="state.dialogVisible"
    destroy-on-close
    @close="closeOpen"
    :modal="true"
    :appendToBody="true"
    width="45vw"
    top="10vh"
    :close-on-click-modal="true"
  >
    <el-tree
      :data="state.feeTypeTreeOptions"
      :check-strictly="true"
      show-checkbox
      check-on-click-node
      accordion
      node-key="label"
      ref="treeRef"
      highlight-current
      :props="state.defaultProps"
      @check-change="handleCheckChange"
      :expand-on-click-node="false"
    >
    </el-tree>

    <el-row justify="end">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </el-row>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, defineProps, defineEmits } from "vue";
import { feeTypeTree } from "../enums";
import NotifMessage from "/@/utils/message/notification";

const emit = defineEmits(["emitFundsCheck"]);

const treeRef = ref(null);

const props = defineProps({
  isshow: {
    type: Boolean,
    default: false
  }
});

watch(
  () => {
    props.isshow;
  },
  () => {
    state.dialogVisible = props.isshow;
  }
);

let state = reactive({
  feeTypeTreeOptions: feeTypeTree,
  defaultProps: {
    children: "children",
    label: "label",
    disabled: "disabled"
  },
  uniqueValue: [],
  dialogVisible: true,
  checkLabel: ""
});

const closeOpen = () => {
  state.dialogVisible = false;
  emit("emitFundsCheck", "");
};

const handleCancel = () => {
  closeOpen();
};

const handleSubmit = () => {
  if (!state.uniqueValue.length) {
    NotifMessage.error("请选择经费类别");
  } else {
    emit("emitFundsCheck", state.checkLabel);
    closeOpen();
  }
};

const handleCheckChange = (data, checkbox) => {
  if (checkbox) {
    // 后端返回的node-key不是id，是moduldCode
    treeRef.value.setCheckedKeys([data.label]);
    treeRef.value.setCurrentKey(data.label);
    state.uniqueValue = treeRef.value.getCheckedKeys();

    // 对设备进行赋值

    state.checkLabel = data.label;
  } else {
    state.uniqueValue = treeRef.value.getCheckedKeys();
    if (state.uniqueValue.length == 0) {
      state.uniqueValue = [];
    }
  }
};
</script>
